package GoodsService

import (
	"context"
	"gdshop-back-end-go/client-api/app/response/GoodsResp"
	toolsDb "gdshop-back-end-go/common/db"
	"gdshop-back-end-go/common/tools"
	"github.com/gogf/gf/frame/g"
)

// GetPager 连表查询版
func GetPager(ctx context.Context, where g.Map, pageIndex, pageSize int, sort string) (*GoodsResp.List, error) {
	count, countErr := toolsDb.GetUnSafaTable(ctx, "goods").As("g").Where(where).
		Fields("1").Count()
	if countErr != nil {
		return nil, countErr
	}

	goodsList := []*GoodsResp.Details{}
	err := toolsDb.GetUnSafaTable(ctx, "goods").As("g").Where(where).Page(
		pageIndex, pageSize,
	).LeftJoin("goods_option go", "g.id = go.goods_id AND go.delete_at < 1").
		Fields("g.*,IFNULL(MIN(go.sell_price),0) AS sell_price,IFNULL(MIN(go.market_price),0) AS market_price").
		Group("g.id").
		Order(getGoodsOrderString(sort)).Structs(&goodsList)

	if err != nil {
		return nil, err
	} else {
		goodsRespList := &GoodsResp.List{
			PageInfo: tools.GetPageInfo(count, pageIndex, pageSize),
		}
		/*if count > 0 {
			// 处理返回数据
			for _, item := range goodsList {
				HandleDetails(ctx, item, false, 1)
			}
		}*/
		goodsRespList.List = goodsList
		goodsRespList.PhotoBaseUrl = g.Cfg().GetString("site.PhotoUrlProfix")
		return goodsRespList, nil
	}
}
